#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
require "doa_subs.pl";

use Scalar::Util qw(looks_like_number);

use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;
my $q = new CGI;
print $q->header;
print $q->start_html('Realm Selector');
print $q->h1({ -align => "CENTER"}, 'Realm Selector');

############################## Main Prog ##############################
#
# This program allows the selection of a different Realm
#
#


print $q->h2({ -align => "CENTER"}, "This is the list of all available Realms");
		
my @pdata;

my $realmfile = 'data/realm.psv';
# open the realm file for read
open(REALM,"<$realmfile") or &dienice("Can't open realm file.");
#	flock(REALM, LOCK_EX);          # lock the file (exclusively)
#	seek(REALM, 0, SEEK_SET);       # rewind to beginning
my @realmf = <REALM>;            	# read entire file
close(REALM);

my $num=1;

foreach my $i (@realmf) 
{
	chomp($i);
	my ($realmn, $realmd) = split(/\|/,$i);

		my $row=$q->td($q->a( {-href=>"/cgi-bin/changerealm2.pl?realm=$realmn"}, $realmn));
		$row=$row.$q->td($realmd);
		push (@pdata, $row);
		$num++;
}

print $q->p({ -align => "CENTER"}, "Click on the Realm number you wish to use");

#print $q->start_form("POST","changerealm2.pl");
print $q->table({-align => "CENTER", -border=>undef,-width=>'50%'},
	$q->Tr({ -align => "CENTER", -valign => "TOP" },$q->th(['Realm Number', 'Realm Name'])),
	$q->Tr({ -align => "CENTER", -valign => "TOP" },\@pdata));
#print $q->textfield('realm');
#print $q->submit('Select Realm','Select Realm');
#print $q->end_form();
print $q->br();
print $q->br();
if ( $level < 10 ) 
{
# print $cgi->textfield(
# -name => 'first_name',
# -id => 'first_name',
# -value => 'Bob Smith',
# -size => 55,
# -maxlength => 128 ); 

#	&dienice("You need to be Super user or above to run this");

	print $q->h2({ -align => "CENTER"}, "To Create a new Realm, put the realm number and name in below and press the Add Realm button");
	print $q->br();
	print $q->start_form("POST","addrealm.pl");
	print	$q->table({ -align => "CENTER", -border=>undef,-width=>'50%'}, 
			$q->Tr({ -align => "CENTER", -valign => "TOP" },$q->th(['Realm Number', 'Realm Name'])),
			$q->Tr({ -align => "CENTER", -valign => "TOP" },
			$q->td($q->textfield( -name => 'realmnum', -id => 'realmnum', -value => '', -size => 3, -maxlength => 3)),
			$q->td($q->textfield( -name => 'realmname', -id => 'realmname', -value => '', -size => 30, -maxlength => 30))),
			$q->td({ -align => "CENTER", -valign => "TOP"}, $q->submit('Add Realm','Add Realm')));
#	print $q->submit('Add Realm','Add Realm');
	print $q->end_form();
}
print $q->end_html;
